from typing import *


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        px = hx = py = hy = 0

        def f(prarent, root, height):
            nonlocal px, hx, py, hy
            if root is None:
                return
            if root.val == x:
                px = prarent
                hx = height
            if root.val == y:
                py = prarent
                hy = height
            f(root.val, root.left, height + 1)
            f(root.val, root.right, height + 1)

        f(-1, root, 0)
        return px != py and hx == hy
